package com.hontech.pastacooking.activity.fragment.sub

import android.view.View
import android.widget.TextView
import androidx.appcompat.widget.SwitchCompat
import com.hontech.pastacooking.R
import com.hontech.pastacooking.activity.window.showProg
import com.hontech.pastacooking.app.AppScope
import com.hontech.pastacooking.conn.testHeater
import com.hontech.pastacooking.model.HeaterStatus
import com.hontech.pastacooking.utils.S
import com.hontech.pastacooking.utils.currentTimestamp
import kotlinx.coroutines.launch

private class HeatStatusCtx() {
    private var last = false
    var sw = false
        private set

    private var begin = currentTimestamp()

    fun update(flag: Boolean) {
        last = sw
        sw = flag
        if (isStart()) {
            begin = currentTimestamp()
        }
    }

    fun openDuration(): Long {
        return currentTimestamp() - begin
    }

    private fun isStart(): Boolean {
        return sw && (!last)
    }

}

class HeaterDelegate(view: View) {

    private val water = view.findViewById<SwitchCompat>(R.id.id_sw_heater_water)
    private val steam = view.findViewById<SwitchCompat>(R.id.id_sw_heater_steam)

    private val tvWaterTime = view.findViewById<TextView>(R.id.id_tv_water_heat_time)
    private val tvSteamTime = view.findViewById<TextView>(R.id.id_tv_steam_heat_time)

    private var updateFlag = false

    private var waterCtx = HeatStatusCtx()
    private var steamCtx = HeatStatusCtx()

    init {
        water.setOnCheckedChangeListener { _, isChecked -> onChecked(1, isChecked) }
        steam.setOnCheckedChangeListener { _, isChecked -> onChecked(2, isChecked) }
    }

    private fun onChecked(id: Int, flag: Boolean) {
        if (updateFlag) {
            return
        }
        val value = if (flag) 0 else 1
        AppScope.launch {
            val w = showProg(water, S.t71)
            try {
                testHeater(id, value)
                w.success(S.t72)
            } catch (e: Exception) {
                e.printStackTrace()
                w.error(e.message!!)
            }
        }
    }

    fun update(status: HeaterStatus) {
        updateFlag = true
        water.isChecked = status.isWaterHeatOpen()
        steam.isChecked = status.isSteamHeatOpen()
        showTime(status)
        updateFlag = false
    }

    private fun showTime(status: HeaterStatus) {
        waterCtx.update(status.isWaterHeatOpen())
        steamCtx.update(status.isSteamHeatOpen())

        if (waterCtx.sw) {
            tvWaterTime.text = "${S.t271}${waterCtx.openDuration()}"
        }
        if (steamCtx.sw) {
            tvSteamTime.text = "${S.t272}${steamCtx.openDuration()}"
        }
    }
}
